<template>
  <div>
    <el-form
      :label-position="labelPosition"
      :model="queryParams"
      ref="queryForm"
      :inline="inline"
      :label-width="labelwidth + 'px'"
    >
      <el-row class="demo-autocomplete">
        <el-col style="margin: 4px 0;padding: 0 8px;box-sizing: border-box;"  v-for="(item, index) in formDataCopy" :key="index" :span="item.span? item.span : 6" v-show="item.isShow??true">
          <el-form-item
            :label="item.label"
            :prop="item.model"
            v-if="item.isShow??true"
            :rules="[
              {
                required: item.required ? item.required : false,
                message: item.message,
                trigger: (item.type == 'selectMultiple' || item.type == 'beginTime')? ['blur','change'] : ['blur'],
              },
            ]"
          >
            <!-- 普通文本框 -->
            <el-input
              :disabled="item.disabled"
              v-model="queryParams[item.model]"
              :placeholder="item.placeholder"
              clearable
              v-if="item.type === 'input'"
              @input="inputRegexpFun($event, item)"
              :maxlength="item.maxlength || 500"
            />
            <el-input
              style="width: 100%"
              type="textarea"
              :disabled="item.disabled"
              v-model="queryParams[item.model]"
              :placeholder="item.placeholder"
              clearable
              v-if="item.type === 'textarea'"
            />
            <!-- 文本框 带前缀-->
            <el-input
              :placeholder="item.placeholder"
              v-model="queryParams[item.model]"
              v-if="item.type === 'inputPrepend'"
              clearable
              :disabled="item.disabled"
            >
              <template slot="prepend">{{ item.selectData }}</template>
            </el-input>
            <!-- 数字文本框 -->
            <el-input-number
              style="width: 100%"
              :disabled="item.disabled"
              v-if="item.type === 'number'"
              v-model="queryParams[item.model]"
              controls-position="right"
              @input="inputFun($event, item)"
              :min="0"
              :max="item.max || 9999999"
              placeholder="请输入"
            ></el-input-number>
            <el-input
              v-if="item.type === 'passWord'"
              :style="{ width: item.width + 'px' }"
              type="password"
              v-model="queryParams[item.model]"
              show-password
              placeholder="请输入"
            ></el-input>
            <!-- 下拉框 -->
            <el-select
              :disabled="item.disabled"
              v-model="queryParams[item.model]"
              :multiple="item.multiple || false"
              filterable
              :placeholder="item.placeholder"
              v-if="item.type === 'select'"
              clearable
              @change="selChangeFun($event, item)"
            >
              <el-option
                v-for="dict in item.selectData"
                :key="dict.value"
                :label="dict[item.labels||'label']"
                :value="dict[item.value||'value']"
              />
            </el-select>
            <!-- 时间选择器 -->
            <el-date-picker
              :disabled="item.disabled"
              v-model="queryParams[item.model]"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              v-if="item.type === 'beginEndTime'"
            >
            </el-date-picker>
            <!-- 单个时间选择器 -->
            <el-date-picker
              v-if="item.type === 'beginTime'"
              :disabled="item.disabled"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeFun($event, item)"
              :value-format="item.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
              v-model="queryParams[item.setTime]"
              :type="item.timeType"
              placeholder="选择时间"
            ></el-date-picker>
            <!-- 下拉多选框 -->
            <el-select
              style="width: 100%"
              filterable 
              :disabled="item.disabled"
              v-model="queryParams[item.model]"
              multiple
              :placeholder="item.placeholder"
              v-if="item.type === 'selectMultiple'"
              @change="selChangeFunMuil($event, item)"
            >
              <el-option
                v-for="dict in item.selectData"
                :key="dict.value"
                :label="dict[item.labels||'label']"
                :value="dict[item.value||'value']"
              >
              <span v-if="item.isslot" style="float: left">{{ dict[item.labels||'label'] }}</span>
              <span
                v-if="item.isslot"
                style="
                  float: right;
                  
                  font-size: 13px;
                "
                ><el-icon v-if="dict.flag != 0"  style="color: red;"><Star /></el-icon></span
              >
              </el-option>
            </el-select>
            <!-- 省份选择 下拉树 -->
            <el-cascader v-if="item.type === 'treeselect'"
            :options="item.selectData" 
            v-model="queryParams[item.model]"
            :placeholder="item.placeholder"
            :props="{ value: 'cityName', label: 'cityName', children: 'children' }"
            clearable />
            <!-- <el-tree-select
              v-if="item.type === 'treeselect'"
              v-model="queryParams[item.model]"
              :data="item.selectData"
              :props="{ value: 'id', label: 'cityName', children: 'children' }"
              value-key="id"
              placeholder="请选择归属部门"
              check-strictly
            /> -->
            <!-- 选择下拉树 -->
            <!-- <treeselect
              :disabled="item.disabled"
              v-model="queryParams[item.model]"
              :options="item.selectData"
              :normalizer="normalizer"
              :placeholder="item.placeholder"
              v-if="item.type === 'treeselect'"
              multiple
              :limit="2"
              style="width: 300px"
            /> -->
            <el-checkbox
              :disabled="item.disabled"
              :true-label="item.trueLabel === 1 ? item.trueLabel : 0"
              :false-label="item.falseLabel"
              v-model="queryParams[item.model]"
              v-if="item.type === 'checkbox'"
            >
              {{ item.name }}
            </el-checkbox>
            <el-radio-group 
              v-if="item.type === 'radio'" 
              v-model="queryParams[item.model]">
              <el-radio label="2">线上</el-radio>
              <el-radio label="1">线下</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6"  style="margin-top: 5px">
          <el-form-item v-show="buttonIsShow" style="padding-left: 40px;box-sizing: border-box;">
            <el-button @click="handleQuery"
              >搜索</el-button
            >
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import request from '@/utils/request'

export default {
  name: "SetUserSelect",
  components: { Treeselect },
  props: {
    isShowUserBtn: {
      type: Boolean,
      default: true,
    },
    labelwidth: {
      type: Number,
      default: 80,
    },
    formData: {
      type: Array,
      default: [],
    },
    queryParams: {
      type: Object,
      default: {},
    },
    buttonIsShow: {
      type: Boolean,
      default: true,
    },
    inline: {
      type: Boolean,
      default: true,
    },
    labelPosition: {
      type: String,
      default: "right",
    },
    types: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      dataTime: "",
      // 选择客户对象
      selectCustomerObj: {},
      parentObj: {},
      // 表单参数
      form: {},
      formDataCopy: [],
      // 弹窗字段
      visible: false,
      type: "add",
      id: null,
    };
  },
  created() {
    this.$nextTick(() => {
      if (this.$route.meta.menuId) {
      } else {
        this.type = "add";
        
      }
    });
  },
  mounted() {
    this.formData?.forEach((val) => {
      if (val.url || val.dict) {
        val.selectData = []
        request({
          url: val.url || ('/system/dict/data/type/' + val.dict),
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 10000,
            ...val.parm
          }
        }).then((res) => {
          (res.rows||res.data)?.forEach((valmin) => {
            valmin.label = valmin.name || valmin.dictLabel || valmin.cityname
            valmin.value = valmin[val.valueIsName] || valmin.dictValue || valmin[val.valueName] || valmin.id 
          })
          val.selectData = res.rows || res.data
          // console.log('val.selectData', val.selectData)
          this.formDataCopy = JSON.parse(JSON.stringify(this.formData));
          this.$emit("updateformData", this.formDataCopy);
        })
      } else {
        this.formDataCopy = JSON.parse(JSON.stringify(this.formData));
      }
    })
  },
  methods: {
    inputRegexpFun(val, item) {
      if (item.regexp == 'number') {
        var re = new RegExp(
          "^(\\-)*(\\d+)\\.(\\d{" + 2 + "}).*$"
        );
        val = val.replace(/[^\d.]/g, "");
        val = val.replace(/^\./g, "");
        val = val.replace(/\.{2,}/g, ".");
        val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        val = val.replace(re, "$1$2.$3");
        this.queryParams[item.model] = val
      }
      
    },
    inputFun(e, item) {
      if (item.model == "adjustPercent") {
        this.$emit("adjustPercentFun", e)
      }
    },
    selChangeFunMuil(e, item) {
      
      if(item.provinceName) {
        let arr = []
        item.selectData.forEach((val) => {
          if (e.includes(val.id)) {
            arr.push(val.cityname)
          }
        })
        this.queryParams[item.provinceName] = arr.join(',')
      }
    },
    selChangeFun(val,item) {
      if (item.dict == "timed_task_type" && item.model == 'type') {
        this.$emit("selChangeFun", {val,...item});
      } else if (item.dict == "variety_mana_owner" && item.model == 'drugOwner') {
        this.$emit("selChangeFuncom", {val,...item});
      } else if (item.electFun) {
        this.$emit("electFun", {val,...item});
      } else if (item.model == 'kind') {
        this.$emit("kindFun", {val,...item});
      } else if (item.model == 'hospital') {
        this.$emit("hospitalFun", {val});
      }
    },
    async submitForm() {
      var valids = null;
      await this.$refs.queryForm.validate((valid) => {
        valids = valid
        if (valid) {
          return this.queryParams;
        } else {
          return false;
        }
      });
      return new Promise((r, j) => {
        if (valids) {
          r(this.queryParams);
        } else {
          j("请把必填项填写完整");
        }
      });
    },
    changeFun(val, data) {
      this.formDataCopy.forEach((item) => {
        if ((item.type == "beginTime" && item.timeType == "daterange") || item.timeType == 'datetimerange') {
          if (val && val.length) {
            this.queryParams[data.model] = val[0];
            this.queryParams[data.endModel] = val[1];
          } else {
            this.queryParams[data.model] = "";
            this.queryParams[data.endModel] = "";
          }
        } else if (item.type == "beginTime" && item.timeType == "date") {
          if (val) {
            this.queryParams[data.model] = val;
          } else {
            this.queryParams[data.model] = "";
          }
        } else if (item.type == "beginTime" && item.timeType == "datetime") {
          if (val) {
            this.queryParams[data.model] = val;
          } else {
            this.queryParams[data.model] = "";
          }
        }
      });
    },
    getlistBaseCusFun() {
      this.$refs.customer.show();
    },
    // 搜索
    handleQuery() {
      this.$emit("selectFunc");
    },        
    resetQuery() {
      if (this.queryParams.setTime) {
        this.queryParams.setTime = null;
      }
      this.$emit("update:queryParams", {
        pageNum: 1,
        pageSize: 10,
        total: this.queryParams.total,
      });
      this.$emit("selectFunc");
    },
    /** 转换商品类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },
    changeStatus(item) {
      item.checked = !item.checked;
    },
    cancel() {
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.listClass {
  max-height: 700px;
  overflow-y: auto;
  .listTitle {
    margin: 10px;
    margin-left: 0px;
  }
  .sortBtnClass {
    margin: 5px;
  }
}
:deep(.el-form-item) {
  margin-bottom: 10px !important;
}
:deep(.el-form--inline .el-form-item) {
  width: 100%;
}
:deep(.el-form-item--default .el-form-item__content) {
  width: 100%;
}
:deep(.el-select) {
  width: 100%;
}
:deep(.el-date-editor.el-input) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-form--inline .el-form-item){
  width: 100%;
}
</style>
